package com.waterfairy.permission

import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry

/**
 * @user water_fairy
 * @mail 995637517@qq.com
 * @date 2021/12/24 3:17 下午
 * @info
 */
class PermissionPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware,
    PluginRegistry.RequestPermissionsResultListener {

    private var activityPluginBinding: ActivityPluginBinding? = null
    lateinit var methodChannel: MethodChannel
    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel = MethodChannel(binding.binaryMessenger, "permission");
        methodChannel.setMethodCallHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {

    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == Methods.REQUEST_PERMISSIONS) {
            Log.i("TAG", "onMethodCall: " + call.method)
            Log.i("TAG", "onMethodCall: " + call.arguments.toString())
            if (call.arguments is ArrayList<*>) {
                val arguments = call.arguments as ArrayList<*>
                if (arguments.size == 2 && arguments[0] is ArrayList<*> && arguments[1] is Int) {
                    val permissionsTemp = arguments[0] as ArrayList<String>
                    val permissions = permissionsTemp.toArray(
                        Array(permissionsTemp.size) { index ->
                            permissionsTemp[index]
                        }
                    )
                    PermissionHandler(
                        result,
                        activityPluginBinding,
                        permissions,
                        arguments[1] as Int
                    ).handle()
                    return
                }
            }
            result.error("-1", "参数错误", null);
        }
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activityPluginBinding = binding
        activityPluginBinding?.addRequestPermissionsResultListener(this)
    }

    override fun onDetachedFromActivity() {
        activityPluginBinding?.removeRequestPermissionsResultListener(this)
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>?,
        grantResults: IntArray?
    ): Boolean {
        return true;
    }

}